<!DOCTYPE html>
<html lang="en">
 
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <script src="./lib/vue-2.4.0.js"></script>
  <link rel="stylesheet" href="./lib/bootstrap-3.3.7.css">
</head>
 
<body>
  <div id="app">
 
 
    <cmt-box @func="loadComments"></cmt-box>
 
 
    <ul class="list-group">
      <li class="list-group-item" v-for="item in list" :key="item.id">
        <span class="badge">评论人： {{ item.user }}</span>
        {{ item.content }}
      </li>
    </ul>
 
 
  </div>
 
 
  <template id="tmpl">
    <div>
 
      <div class="form-group">
        <label>评论人：</label>
        <input type="text" class="form-control" v-model="user">
      </div>
 
      <div class="form-group">
        <label>评论内容：</label>
        <textarea class="form-control" v-model="content"></textarea>
      </div>
 
      <div class="form-group">
        <input type="button" value="发表评论" class="btn btn-primary" @click="postComment">
      </div>
 
    </div>
  </template>
 
  <script>

      //创建模板对象
      var commentBox={
          data(){
             return{
                user:'',
                content:'',     
             }
          },
          template:'#tmpl',
          methods:{
             //上传用户输入的信息到当地
             postComment(){
                 //获取用户输入的信息
                 var comment={id:Date.now(),user:this.user,content:this.content}
                 //获取本地的localstorage信息
                 var list=JSON.parse(localStorage.getItem('cmts')||'[]')
                 //把comment添加到list中
                 list.unshift(comment)
                 //重新设置localstrorage
                 localStorage.setItem('cmts',JSON.stringify(list))
                 //清空表格
                 this.user=this.content=''
                 this.$emit('func')
             }
          }
      } 
  
    // 创建 Vue 实例，得到 ViewModel
    var vm=new Vue({
      el:'#app',
      data:{
        list:[
          {id:Date.now(),user:'李白',content:'天生我才必有用'}
        ]
      },
      created(){
         //将本地的信息展现出来
         this.loadComments()
      },
      methods:{
         //将本地的信息展现出来
         loadComments(){
            var list=JSON.parse(localStorage.getItem('cmts')||'[]')
            this.list=list
         }
      },
      components:{
        'cmt-box':commentBox
      }
    });
  </script>
</body>
 
</html>















